package fun.codedesign.jdk.socket.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Date;
import java.util.Iterator;
import java.util.Set;

/**
 * @author zengjian
 * @create 2018-04-17 10:04
 * @since 1.0.0
 */
public class NioServer implements Runnable {

    private Selector selector; // 多路复用器
    private ServerSocketChannel serverSocketChannel; //服务端通道
    private volatile boolean stop; // 停止标志位

    public NioServer(int port) {
        try {
            selector = Selector.open();
            System.out.println("打开多路复用器...");
            serverSocketChannel = ServerSocketChannel.open();
            System.out.println("打开服务端通道...");
            // 配置非阻塞
            serverSocketChannel.configureBlocking(false);
            // 绑定连接端口和最大连接数
            serverSocketChannel.bind(new InetSocketAddress(port), 1024);
            serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
            System.out.println("服务端启动，端口号:" + port);
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(1);
        }
    }

    public void stop() {
        this.stop = true;
    }

    @Override
    public void run() {
        try {
            while (!stop) {
                // 每隔1s轮询
                selector.select(1000);
                Set<SelectionKey> selectionKeys = selector.selectedKeys();
                Iterator<SelectionKey> iterable = selectionKeys.iterator();
                SelectionKey key = null;
                while (iterable.hasNext()) {
                    key = iterable.next();
                    iterable.remove();
                    try {
                        // 委托给私有方法
                        handleInput(key);
                    } catch (Exception e) {
                        if (key != null) {
                            key.cancel();
                        }
                        if (key.channel() != null) {
                            key.channel().close();
                        }
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 关闭多路复用器后，上面的channel和pipe都会自动去注册并且关闭，不需要重复释放
        if (selector != null) {
            try {
                selector.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


    }

    private void handleInput(SelectionKey key) throws IOException {
        // 根据key的类型，进行处理
        if (key.isValid()) {
            // 新接入的请求消息
            if (key.isAcceptable()) {
                // 接收新的连接
                ServerSocketChannel ssc = (ServerSocketChannel) key.channel();
                SocketChannel sc = ssc.accept();
                sc.configureBlocking(false);
                // 增加连接到多路复用器
                sc.register(selector, SelectionKey.OP_READ);
            }
            if (key.isReadable()) {
                SocketChannel sc = (SocketChannel) key.channel();
                ByteBuffer readBuffer = ByteBuffer.allocate(1024);
                int readBytes = sc.read(readBuffer);
                if (readBytes > 0) {
                    readBuffer.flip();
                    byte[] bytes = new byte[readBuffer.remaining()];
                    readBuffer.get(bytes);
                    String body = new String(bytes, "utf-8");
                    System.out.println("server accept:" + body);
                    String currentTime = "QUERY TIME ORDER".equalsIgnoreCase(body) ? new Date().toString() : "BAD ORDER";
                    // 异步写回
                    doWrite(sc, currentTime);
                }
            }
        }
    }

    private void doWrite(SocketChannel channel, String response) throws IOException {
        if (response != null && response.trim().length() > 0) {
            byte[] bytes = response.getBytes();
            ByteBuffer writeBuffer = ByteBuffer.allocate(bytes.length);
            writeBuffer.put(bytes);
            writeBuffer.flip();
            channel.write(writeBuffer);
        }
    }

    public static void main(String[] args) {
        int port = 8080;
        new Thread(new NioServer(port)).start();
    }
}
